package com.example.user.concurrent;

import com.example.user.bo.Person01BO;
import com.example.user.mapper.ds1.UserMapper1;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 测试多线程事务.
 *
 * @param
 */
@Service
@Transactional(value = "transactionManager1")
public class ConcurrentService {

    @Resource
    SqlContext sqlContext;
    @Autowired
    private UserMapper1 userMapper1;

    @Autowired
    private DataSourceTransactionManager transactionManager1;

    public void saveThread(List<Person01BO> list) throws SQLException {
        Connection connection = sqlContext.getSqlSession().getConnection();
        System.out.println("isolation：" + connection.getTransactionIsolation());

        Person01BO boInit = new Person01BO();
        boInit.setId("9999999");
        boInit.setSapName("initname");
        userMapper1.insert(boInit);
        List<Person01BO> list1 = getTestDate();
        int i = userMapper1.insertList(list1);
        System.out.println(i);

    }

    public void saveThread2(List<Person01BO> list) throws SQLException, InterruptedException {
        // 获取数据库连接,获取会话(内部自有事务)
        SqlSession sqlSession = sqlContext.getSqlSession();
        Connection connection = sqlSession.getConnection();
        // 设置手动提交
        connection.setAutoCommit(false);

        Person01BO boInit = new Person01BO();
        boInit.setId("9999999");
        boInit.setSapName("initname");
        userMapper1.insert(boInit);

        //获取执行器
        ExecutorService service = ExecutorConfig.getThreadPool();
        List<Callable<Integer>> callableList = new ArrayList<>();
        //拆分list
        int size = 3;
        List<List<Person01BO>> lists = averageAssign(list, size);
        CountDownLatch insertLatch = new CountDownLatch(size);
        CountDownLatch rollbackLatch = new CountDownLatch(size);
        CountDownLatch endLatch = new CountDownLatch(size);
        //执行的线程
        Thread[] threadArray = new Thread[lists.size()];
        //监控子线程执行完毕,再执行主线程,要不然会导致主线程关闭,子线程也会随着关闭
        AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        for (int i = 0; i < lists.size(); i++) {
            List<Person01BO> innerList = lists.get(i);
            //使用返回结果的callable去执行,
            threadArray[i] = new Thread("insertThread:" + i) {
                @Override
                public void run() {
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                    TransactionStatus status = transactionManager1.getTransaction(def);
                    int j = 0;
                    try {
                        try {
                            j = userMapper1.insertList(innerList);
                            System.out.println("成功存入" + j + "条" + innerList);
                        } catch (Exception e) {
                            //e.printStackTrace();
                            rollbackLatch.countDown();
                        } finally {
                            insertLatch.countDown();
                        }
                        System.out.println(Thread.currentThread().getName() + "在等待所有子线程完毕");
                        insertLatch.await();

                        if (rollbackLatch.getCount() == size) {
                            System.out.println(Thread.currentThread().getName() + "commit");
                            transactionManager1.commit(status);
                        } else {
                            System.out.println(Thread.currentThread().getName() + "rollback");
                            transactionManager1.rollback(status);
                        }
                    } catch (Exception e) {
                    } finally {
                        endLatch.countDown();
                    }

                }
            };
        }
        //执行子线程
        for (int i = 0; i < size; i++) {
            service.execute(threadArray[i]);
        }
        insertLatch.await();
        //所有sql执行完毕如果所有分支成功则提交
        if (rollbackLatch.getCount() == lists.size()) {
            System.out.println("main commit");
            connection.commit();
        } else {
            System.out.println("main rollback");
            connection.rollback();
        }
        System.out.println("主程序执行完毕");
        endLatch.await();
        System.out.println("all task is over");


    }

    public void saveThread3(List<Person01BO> list) throws SQLException, InterruptedException {
        // 获取数据库连接,获取会话(内部自有事务)
        SqlSession sqlSession = sqlContext.getSqlSession();
        Connection connection = sqlSession.getConnection();
        // 设置手动提交
        connection.setAutoCommit(false);

        Person01BO boInit = new Person01BO();
        boInit.setId("9999999");
        boInit.setSapName("initname");
        userMapper1.insert(boInit);

        //获取执行器
        ExecutorService service = ExecutorConfig.getThreadPool();
        List<Callable<Integer>> callableList = new ArrayList<>();
        //拆分list
        int size = 3;
        List<List<Person01BO>> lists = averageAssign(list, size);
        CountDownLatch insertLatch = new CountDownLatch(size);
        CountDownLatch rollbackLatch = new CountDownLatch(size);
        CountDownLatch endLatch = new CountDownLatch(size);
        //执行的线程
        Thread[] threadArray = new Thread[lists.size()];
        //监控子线程执行完毕,再执行主线程,要不然会导致主线程关闭,子线程也会随着关闭
        AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        List<Callable<TransactionStatus>> callables = new ArrayList<>(size);
        for (int i = 0; i < lists.size(); i++) {
            List<Person01BO> innerList = lists.get(i);
            //使用返回结果的callable去执行,
            Callable<TransactionStatus> callable = new Callable<TransactionStatus>() {
                @Override
                public TransactionStatus call() throws Exception {
                    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
                    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
                    TransactionStatus status = transactionManager1.getTransaction(def);
                    int j = 0;
                    try {
                        j = userMapper1.insertList(innerList);
                        System.out.println("成功存入" + j + "条" + innerList);
                    } catch (Exception e) {
                        rollbackLatch.countDown();
                    } finally {
                        insertLatch.countDown();
                    }
                    return status;
                }
            };
            callables.add(callable);
        }
        List<Future<TransactionStatus>> futures = service.invokeAll(callables);
        //执行子线程
        insertLatch.await();
        //所有sql执行完毕如果所有分支成功则提交
        if (rollbackLatch.getCount() == lists.size()) {
            System.out.println("main commit");
            connection.commit();
        } else {
            System.out.println("main rollback");
            connection.rollback();
        }
        System.out.println("主程序执行完毕");
        endLatch.await();
        System.out.println("all task is over");
        //应该写入final

        Runtime.getRuntime().addShutdownHook(new Thread(()->{
            System.out.println("mainThread is shutting down");
//            try {
//                connection.close();
//            } catch (SQLException e) {
//                throw new RuntimeException(e);
//            }
            //service.shutdown();
        }));

    }

    /**
     * 平均拆分list方法.
     *
     * @param source
     * @param n
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remaider = source.size() % n;
        System.out.println(remaider);
        int number = source.size() / n;
        System.out.println(number);
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remaider > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remaider--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

    public static List<Person01BO> getTestDate() {
        List<Person01BO> list = new ArrayList<>();
        for (int i = 300; i < 310; i++) {
            Person01BO bo = new Person01BO();
            bo.setId(Integer.valueOf(i).toString());
            bo.setSapName("name");
            list.add(bo);
        }
        return list;
    }

    public static void main(String[] args) {
        List<Person01BO> list = getTestDate();
        List<List<Person01BO>> lists = averageAssign(list, 3);
        lists.forEach(System.out::println);
    }
}